package com.baihan.angus.app.game.common.util.my_span;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.baihan.angus.app.game.basic.BaseApplication;
import com.baihan.angus.app.game.basic.utils.ComUtil;

public class RoundBgSpan extends ReplacementSpan {
    private final int radius = 10;
    private final int paddingSpace = ComUtil.Dp2Px(BaseApplication.getApplication(), 5);
    private Paint mPaint;

    private boolean withBorder;
    private int bgColor;
    private int textColor;
    private int borderColor;

    private int spaceWidth;
    private int baselineOffset;

    public RoundBgSpan(int bgColor, int textColor) {
        this.bgColor = bgColor;
        this.textColor = textColor;
    }

    public RoundBgSpan(int bgColor, int textColor, int borderColor) {
        this.withBorder = true;
        this.bgColor = bgColor;
        this.textColor = textColor;
        this.borderColor = borderColor;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        float originalTextSize = paint.getTextSize();
        mPaint = new Paint();
        mPaint.setTextSize(originalTextSize);
        mPaint.setColor(textColor);
        mPaint.setAntiAlias(true);
        spaceWidth = (int) mPaint.measureText(text, start, end) + radius * 2 + paddingSpace * 2;
        int originalBaselineToMiddleLineDistance = (int) ((paint.descent() - paint.ascent()) * 0.5 - paint.descent());
        int newBaselineToMiddleLineDistance = (int) ((mPaint.descent() - mPaint.ascent()) * 0.5 - mPaint.descent());
        baselineOffset = originalBaselineToMiddleLineDistance - newBaselineToMiddleLineDistance;
        return spaceWidth;
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        //绘制文字
        paint.setColor(bgColor);//设置背景颜色
        paint.setAntiAlias(true);// 设置画笔的锯齿效果
        RectF oval = new RectF(x , y + paint.ascent() - ComUtil.Dp2Px(BaseApplication.getApplication(),8), x + spaceWidth, y + paint.descent() + ComUtil.Dp2Px(BaseApplication.getApplication(),8));
        //设置文字背景矩形，x为span其实左上角相对整个TextView的x值，y为span左上角相对整个View的y值。paint.ascent()获得文字上边缘，paint.descent()获得文字下边缘
        canvas.drawRoundRect(oval, radius, radius, paint);//绘制圆角矩形，第二个参数是x半径，第三个参数是y半径
        paint.setColor(textColor);//设置/恢复画笔的文字颜色

        canvas.drawText(text.toString().substring(start, end), x + paddingSpace + radius, y - baselineOffset, mPaint);//绘制文字
    }
}
